# coding:utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)

browser.get('http://wljy.whut.edu.cn/web/login.htm')
# browser.get('http://wljy.whut.edu.cn/web/admissionprocess.htm')
studyIndex = 0


def login(username, password):

    username_element = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#yonghuming')))
    password_element = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#mima')))
    login_btn = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#loginBtn')))
    username_element.send_keys(username)
    password_element.send_keys(password)
    login_btn.click()


def login2(username, password):
    # Setting the value of email input field
    fill_username = f'var element = document.getElementById("email"); element.value = "{username}";'
    browser.execute_script(fill_username)
    # Setting the value of password input field
    fill_password = f'var element = document.getElementById("password"); element.value = "{password}";'
    browser.execute_script(fill_password)


def my_courses():
    courses_element = wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#curriculum')))
    # 点击无效 不清楚什么原因
    courses_element.click()


def my_courses2():
    wait.until(EC.presence_of_element_located(
        (By.CSS_SELECTOR, '#curriculum')))
    js = f'document.getElementById("curriculum").click();'
    browser.execute_script(js)


def course_c_programing():
    wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#learnCourse')))
    js = f'document.getElementById("learnCourse").click();'
    browser.execute_script(js)
    time.sleep(2)


# （随机/顺序）选择章节课程
def select_course():
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.study')))
    print('select_course')
    js = f'''
      let studyCourse = document.querySelectorAll(".study");
      let randomStudy = Math.floor(Math.random()*(studyCourse.length));
      studyCourse[randomStudy].click();
    '''
    browser.execute_script(js)
    # 如果没有switch做窗口切换的话，即使有打开新的窗口，浏览器还是会focus在原来的窗口
    print(
        f"2. routing Configure Page had been opened, currentTitle = {browser.title}, currentHandle = {browser.current_window_handle}"
    )

    # 拿到所有的窗口
    allHandles = browser.window_handles
    print(f"3. allHandles = {allHandles}")

    # 第一种思路：按照handle，从淘宝窗口切换到路由器配置窗口
    routeWindowHandle = 0
    routeTitle = 'None'
    for handle in allHandles:
        if handle != browser.current_window_handle:
            browser.switch_to_window(handle)
            routeWindowHandle = browser.current_window_handle
            routeTitle = browser.title
            break
    print(
        f"4. switch to routeWindow, routeWindowHandle = {routeWindowHandle}, routeTitle = {routeTitle}, currentHandle = {browser.current_window_handle}, currentTitle = {browser.title}"
    )


# 选择节课程
def select_section():
    wait.until(
        EC.presence_of_element_located(
            (By.CSS_SELECTOR, 'a.level2[title="视频讲解"]')))
    print('select_section')
    js = f'''
      let section = document.querySelectorAll('a.level2[title="视频讲解"]');
      let randomSection = Math.floor(Math.random()*(section.length));
      section[randomSection].click();
    '''
    browser.execute_script(js)
    time.sleep(2)


def play_video():
    wait.until(
        EC.presence_of_element_located((By.CSS_SELECTOR, '#ckplayer_a1')))
    print('play_video')
    js_play_video = f'''
      let player;
      player = document.querySelector('#ckplayer_a1');
      player.play();
      let duration = player.duration;
      setTimeout(() = {{
        console.log(duration)
      }}, 3000);
      setTimeout(()=>{{
        // 做笔记 or 发评论
      }}, duration);
    '''
    browser.execute_script(js_play_video)
    time.sleep(2)


def main():
    try:
        login('13434792339', '253658')
        my_courses2()
        course_c_programing()
        select_course()
        select_section()
        play_video()
    except Exception as e:
        print('error', e)
        # browser.close()
    finally:
        pass


if __name__ == '__main__':
    main()
